package JAVA300.第十一章多线程;

/**
 * 取钱线程-添加同步方法--错误锁
 */

public class thread_15_synchronized1_safe2 {
    public static void main(String[] args) {

        Accounts account = new Accounts(500,"hqqs money");
        SafeDrawing hqq = new SafeDrawing(account,100,"hqq-hpv");
        SafeDrawing qyh = new SafeDrawing(account,300,"qyh-nike");
        hqq.start();
        qyh.start();


    }

}

class Accounts {
     int money;
     String name;

    public Accounts(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

class SafeDrawing extends Thread{
    Accounts account;//取得账户
    int drawingMoney;//单次取得钱数
    int gettotal;//总共取得钱数

    public SafeDrawing(Accounts account, int drawingMoney,String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        test();

    }
    //目标锁定失败，应该锁的是对象

    public synchronized void test(){


        //添加安全控制--防止出现负数-控制不住 引出第三个不安全类
        if ( account.money - drawingMoney <0){
            return;
        }

        //模拟网络延时
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        gettotal += drawingMoney;
        System.out.println(this.getName()+"-->账户余额为："+account.money);
        System.out.println(this.getName()+"-->口袋的钱为："+gettotal);

    }
}


